package com.blog.controller;

import com.blog.pojo.User;
import com.blog.service.LoginService;
import com.blog.service.UserService;
import com.blog.service.impl.LoginServiceImpl;
import com.blog.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;

@WebServlet("/loginServlet")
public class LoginServlet extends BaseServlet{
    private LoginService loginUserService=new LoginServiceImpl();
    private UserService userService=new UserServiceImpl();

    //登录
    public String login(HttpServletRequest request, HttpServletResponse response){

        //1.获取参数
        String username=request.getParameter("username");
        String password =request.getParameter("password");
//        int roleId = Integer.parseInt(request.getParameter("roleId"));
        //2.调用业务方法
        User loginUser = loginUserService.login(username, password);
        // 3. 根据返回结果分支
        if (loginUser == null) {
            // 3.1 用户名不存在 → 去注册
            return "forward:register.jsp";
        } else {
            // 3.3 都正确 → 登录成功，存 Session，去首页
            request.getSession().setAttribute("user", loginUser);
            return "forward:index.jsp";
        }

    }



    //注册
    public String register(HttpServletRequest request, HttpServletResponse response){
        //1.获取参数
        String username=request.getParameter("username");
        String password =request.getParameter("password");
        String phone=request.getParameter("phone");
        //2.调用业务方法

        User user = new User();
        user.setPassword( password);
        user.setCreatedAt(LocalDateTime.now());
        user.setUsername(username );
        user.setPhone(phone);
        User existingUser  = userService.findByUserName(username);

        if(existingUser!=null){
            return "forward:/register.jsp";
        }

        User loginUser=  userService.addUser(user);
      if(loginUser!=null){
          HttpSession session=request.getSession();
          session.setAttribute("user",loginUser);
          return "forward:/index.jsp";
      }else{
          return "forward:/register.jsp";
      }
    }
    //退出登录
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        // 1. 获取当前 session
        HttpSession session = req.getSession(false);
        if (session != null) {

            session.removeAttribute("user");
            session.invalidate();
        }

        return "forward:/login.jsp";
    }
}
